﻿using System;
using System.Linq;
using System.Collections.ObjectModel;
using Microsoft.WowAddonStudio.FrameXml.Serialization.LayoutFrames;

namespace Microsoft.WowAddonStudio.FrameXml.Serialization.Support
{
    [Serializable]
    public class LayoutFrameList : Collection<LayoutFrame>
    {
        /// <summary>
        /// Inserts an element into the <see cref="T:System.Collections.ObjectModel.Collection`1"/> at the specified index.
        /// </summary>
        /// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param>
        /// <param name="item">The object to insert. The value can be null for reference types.</param>
        /// <exception cref="T:System.ArgumentOutOfRangeException">
        /// 	<paramref name="index"/> is less than zero.
        /// -or-
        /// <paramref name="index"/> is greater than <see cref="P:System.Collections.ObjectModel.Collection`1.Count"/>.
        /// </exception>
        protected override void InsertItem(int index, LayoutFrame item)
        {
            if (item.Virtual)
            {
                // Check whether the item has inherited item.
                var inheritedLayoutFrame = this.Items.SingleOrDefault(i => i.Name == item.Inherits);

                if (inheritedLayoutFrame != null)
                {
                    // Insert new item after inherited item.
                    int ingheritedIndex = this.IndexOf(inheritedLayoutFrame);
                    base.InsertItem(ingheritedIndex + 1, item);
                }
                else
                {
                    // If there is no inherited item inset it into the first place of the list.
                    base.InsertItem(0, item);
                }
            }
            else
            {
                // If the item is not virtual insert it into the end of the list.
                base.InsertItem(index, item);
            }
        }

        /// <summary>
        /// Resets the item.
        /// </summary>
        /// <param name="layoutFrame">The layout frame.</param>
        public void ResetItem(LayoutFrame layoutFrame)
        {
            this.Remove(layoutFrame);

            InsertItem(this.Count, layoutFrame);
        }
    }
}
